package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.mapper.OrderDetailMapper;
import com.bwie.mapper.OrderRecordMapper;
import com.bwie.mapper.ProdInfoMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.pojo.*;
import com.bwie.service.IUserService;
import com.bwie.utils.R;
import com.bwie.vo.OrderDetailVo;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Jwts;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.OrderMapper;
import com.bwie.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService{

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    ProdInfoMapper prodInfoMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    OrderRecordMapper orderRecordMapper;

    @Autowired
    HttpServletResponse response;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    IUserService iUserService;

    @Override
    public R orderList(PageInfoVo pageInfoVo) {
        Page<Order> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        QueryWrapper<Order> wrapper = new QueryWrapper<>();


        //关键字
        if(StringUtils.isNotEmpty(pageInfoVo.getKeyWord())){
            wrapper.lambda().like(Order::getProdInfo,pageInfoVo.getKeyWord()).or().eq(Order::getOrderId,pageInfoVo.getKeyWord());
        }
        //订单状态精确查询
        if(pageInfoVo.getStatus()!=null){
            wrapper.lambda().eq(Order::getOrderStatus,pageInfoVo.getStatus());
        }
        if(pageInfoVo.getType()!=null){
            wrapper.lambda().eq(Order::getOrderType,pageInfoVo.getType());
        }




        wrapper.lambda().orderByDesc(Order::getOrderId);
        Page<Order> orderPage = orderMapper.selectPage(page, wrapper);

        //把多图片展示出来
        for (Order record : orderPage.getRecords()) {
            List<String> imagesList=orderMapper.getOrderImageList(record.getOrderId());
            List<String> imagesLi = new ArrayList<>();
            if(imagesList!=null && imagesList.size()>0){
                for (String s : imagesList) {
                    if(s!=null){
                        List<String> list = JSON.parseArray(s, String.class);
                        imagesLi.addAll(list);
                    }
                }
            }
            record.setImagesList(imagesLi);
        }
//        String token = request.getHeader("token");
//        Integer userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("userId", Integer.class);
//        String key="order-list"+userId;
//        redisTemplate.opsForValue().set(key,JSON.toJSONString(orderPage.getRecords()));

        return R.ok().setData(orderPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addOrder(List<ProdInfo> infoList) {
        //通过token获取订单信息
        String token = request.getHeader("token");
        Integer userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("userId", Integer.class);
        String userName = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("userName", String.class);
        //扣减并更新库存
        BigDecimal totalAmount = new BigDecimal("0");
        StringBuilder prodNames = new StringBuilder();
        //检查库存
        for (ProdInfo prodInfo : infoList) {
            ProdInfo prodInfo1 = prodInfoMapper.selectById(prodInfo.getInfoId());
            if(prodInfo1.getProdStock()<prodInfo.getBuyNum()){
                throw new RuntimeException("库存不足");
            }

            //扣减订单并更新
            prodInfo1.setProdStock(prodInfo1.getProdStock()-prodInfo.getBuyNum());
            prodInfoMapper.updateById(prodInfo);

            //计算订单金额
            totalAmount=totalAmount.add(prodInfo.getProdPrice().multiply(new BigDecimal(prodInfo.getBuyNum())));
            //拼接商品名称
            if(prodNames.length()>0){
                prodNames.append(",");
                prodNames.append(prodInfo.getProdName());
            }else{
                prodNames.append(prodInfo.getProdName());
            }
        }

        //创建订单
        Order order = new Order();
        //雪花算法生成订单编号
        long id = IdUtil.getSnowflake(1, 1).nextId();
        order.setOrderNo(""+id);
        order.setOrderStatus(0);
        order.setUserId(userId);
        order.setOrderAmount(totalAmount);
        order.setProdInfo(prodNames.toString());
        order.setCreateTime(new Date());
        order.setCreateBy(userName);
        order.setOrderType(1);

        orderMapper.insert(order);
        //创建订单明细
        for (ProdInfo prodInfo : infoList) {
            OrderDetail orderDetail = new OrderDetail();
            //关联订单
            orderDetail.setOrderId(order.getOrderId());
            orderDetail.setProdId(prodInfo.getProdId());
            orderDetail.setBuyNum(prodInfo.getBuyNum());
            orderDetail.setBuyPrice(prodInfo.getProdPrice());
            orderDetail.setInfoId(prodInfo.getInfoId());
            orderDetail.setCreateBy(userName);
            orderDetail.setCreateTime(new Date());

            orderDetailMapper.insert(orderDetail);
        }
        //新增订单记录
        OrderRecord orderRecord = new OrderRecord();
        orderRecord.setOrderId(order.getOrderId());
        orderRecord.setOptRecord("用户创建订单");
        orderRecord.setCreateTime(new Date());
        orderRecord.setCreateBy(userName);
        orderRecordMapper.insert(orderRecord);
        return R.ok();
    }


    @Override
    public void exportOrderList(Integer userId) {

        //创建导出工具
        ExcelUtil<Order> excelUtil = new ExcelUtil<>(Order.class);

        //从缓存中获取订单列表
        String key="order-list"+userId;
        String s = redisTemplate.opsForValue().get(key);
        List<Order> tbOrderList = JSON.parseArray(s, Order.class);
        //导出excel文件
        excelUtil.exportExcel(response,tbOrderList,"订单列表");
    }

    @Override
    public R getOrderInfoById(Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        if(order==null){
            return R.error().setMsg("订单不存在");
        }

        //2获取用户信息
        R r = iUserService.getUserInfoById(order.getUserId());
        if(r.getCode()!=200){
            return r;
        }
        String s = JSON.toJSONString(r.getData());
        User user = JSON.parseObject(s, User.class);
        order.setUser(user);

        //3根据订单ID获取商品列表
        List<OrderDetailVo> orderDetailVoList=orderMapper.getOrderDetailList(orderId);
        order.setDetailList(orderDetailVoList);

        //4订单记录
        List<OrderRecord> recordList= orderRecordMapper.selectList(
                new QueryWrapper<OrderRecord>().lambda()
                        .eq(OrderRecord::getOrderId, orderId)
                        .orderByAsc(OrderRecord::getCreateTime)
        );
        order.setRecordList(recordList);


        return R.ok().setData(order);
    }

}
